package rabbitas.flow{
	import flash.events.ProgressEvent;
	import flash.events.EventDispatcher;
	import flash.events.Event;
	import rabbitas.LiveCycleManager;
	import flash.events.IEventDispatcher;
	/**
	 * @author martindyrby
	 */
	public class DiligentObjectInitFlow extends EventDispatcher implements IRabbitFlow{
		private var executionMethod:Function;
		private var completeCallback:Function;
		private var liveCycleManager:LiveCycleManager;
		private var instances:Array;
		private var count:int=0;
		
		public function init(executionMethod:Function,completeCallback:Function,progressDispatcher:IEventDispatcher,progressEvent:String):void{
			this.executionMethod=executionMethod;
			this.completeCallback=completeCallback;
			progressDispatcher.addEventListener(progressEvent,progressHandler,false,0,true);
			liveCycleManager=LiveCycleManager(progressDispatcher);
		}

		private function progressHandler(event:Event):void{
			checkInstances();
			dispatchEvent(new ProgressEvent(ProgressEvent.PROGRESS,false,false,++count,instances.length));
		}

		public function execute():void{
			instances = executionMethod.call();
			checkInstances();
		}

		private function checkInstances():void{
			
			for(var i:int=0; i<instances.length;i++){
				if(liveCycleManager.instanceIsPendingInit(instances[i])) return;
			}

			completeCallback.call();
		}

		public function destroy():void{
			executionMethod=null;
			completeCallback=null;
			liveCycleManager=null;
		}
	}
}
